<template>
  <div>
    <!-- <div class="box-shadow">
      <px-tabs v-model="activeArea" class="equipment-tabs" style="position: relative; top: -10px; background: none" @tab-change="activeTabChange">
        <px-tab-pane v-for="item in areaList" :key="item.id" :name="item.itemName">
          <template #label>
            <p class="pane-bottom">{{ item.itemName }}</p>
            <p class="pane-line" />
          </template>
        </px-tab-pane>
      </px-tabs>
      <px-form ref="queryRef" class="custom-form-ui-new" :inline="true" label-width="68px">
        <px-form-item style="border: none">
          <px-radio-group v-model="filterType" @change="filterTypeChange">
            <px-radio-button v-for="(item, index) in filterTypeList" :key="index" :label="item.label">{{ item.label }}</px-radio-button>
          </px-radio-group>
        </px-form-item>
        <px-form-item label="日期" style="width: 400px">
          <px-date-picker
            v-model="dateRange2"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="false"
          />
        </px-form-item>
        <px-form-item>
          <px-button type="primary" @click="getChartData">查询</px-button>
          <px-button @click="resetQuery2">重置</px-button>
        </px-form-item>
      </px-form>

      <div class="box">
        <div class="left"><echartsChart ref="chartRef1" :boxShadow="false" :options="chartOptions_1" /></div>
      </div>
    </div> -->
    <div class="box-shadow">
      <px-form ref="queryRef" class="custom-form-ui-new" :model="queryParams" :inline="true" label-width="68px">
        <px-form-item label="化滤更换日期" style="width: 460px">
          <px-date-picker
            v-model="dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="false"
          />
        </px-form-item>
        <px-form-item>
          <px-button type="primary" @click="getList">查询</px-button>
          <px-button @click="resetQuery">重置</px-button>
          <px-button v-has="'MACHINE_REPORT_FFU_EXPORT'" type="primary" plain @click="handleExport">导出</px-button>
        </px-form-item>
      </px-form>
      <px-button v-has="'MACHINE_REPORT_FFU_ADDTIMECOL'" type="primary" plain icon="plus" style="margin-bottom: 12px" @click="addColCount"
        >追加时间列</px-button
      >
      <px-table
        v-loading="loading"
        height="calc(100vh - 268px)"
        :header-cell-style="{ background: '#e7eefb', color: '#000' }"
        border
        :data="tableList"
      >
        <template #empty>
          <px-empty />
        </template>
        <px-table-column type="index" label="序号" width="60" align="center" />
        <px-table-column label="区域" align="center" prop="area" width="70" />
        <px-table-column label="化滤类型" align="center" prop="filterType" min-width="110" />
        <px-table-column label="首次安装" align="center" prop="firstInstallDate" min-width="110">
          <template #default="scope">
            {{ scope.row.firstInstallDate ? dayjs(scope.row.firstInstallDate).format("YYYY-MM-DD") : "" }}
          </template>
        </px-table-column>
        <px-table-column label="上次更换" align="center" prop="lastInstallDate" min-width="110">
          <template #default="scope">
            {{ scope.row.lastInstallDate ? dayjs(scope.row.lastInstallDate).format("YYYY-MM-DD") : "" }}
          </template>
        </px-table-column>
        <px-table-column label="预计更换时间" align="center" prop="nextInstallDate" min-width="110">
          <template #default="scope">
            {{ scope.row.nextInstallDate ? dayjs(scope.row.nextInstallDate).format("YYYY-MM-DD") : "" }}
          </template>
        </px-table-column>
        <px-table-column label="预计寿命（月）" align="center" prop="lifeTotal" />
        <px-table-column label="距更换还剩（月）" align="center" prop="lifeLeft" />
        <px-table-column v-for="n in colCount" :key="n" label="更换时间" align="center" prop="installHistory" min-width="110">
          <template #default="scope">
            {{ scope.row.installHistory[n - 1] ? dayjs(scope.row.installHistory[n - 1]).format("YYYY-MM-DD") : "" }}
          </template>
        </px-table-column>
      </px-table>
    </div>
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "FFULedger"
});
import { PxMessage, PxMessageBox } from "px-ui";
import { queryDictData } from "@/api/common";
import { getCurrentInstance, onMounted, reactive, ref, toRefs, nextTick } from "vue";
import { getToken } from "@/utils/auth";
const { VITE_FANRUAN_BASE_URL } = import.meta.env;
import dayjs from "dayjs";
import echartsChart from "@/views/common/components/echartsChart/index.vue";
import { getFabZone, queryChildByTypeCodeAndItemValue, queryCountFilterUsage, queryCorrelationFactorS, ffuLifespan } from "@/api/machineClass";

const { proxy }: any = getCurrentInstance();
const areaList = ref([]);
const filterTypeList = ref([
  {
    label: "酸性",
    value: "酸性",
    num: 0,
    color: "#4786FF"
  },
  {
    label: "碱性",
    value: "碱性",
    num: 0,
    color: "#14C7C7"
  },
  {
    label: "VOC",
    value: "VOC",
    num: 0,
    color: "#FFB266"
  },
  {
    label: "RC",
    value: "RC",
    num: 0,
    color: "#8B8AE6"
  },
  {
    label: "ulPA",
    value: "ulPA",
    num: 0,
    color: "#FFA299"
  }
]);

const activeArea = ref("LITHO");
const filterType = ref("酸性");

const chartRef1 = ref();
const chartRef2 = ref();
const chartOptions_1 = ref(null);
const chartOptions_2 = ref(null);

const activeTabChange = () => {
  console.log("activeArea,", activeArea.value);
  getChartData();
};
const filterTypeChange = () => {
  console.log("filterType,", filterType.value);
  getChartData();
};
// 获取区域列表
const queryAreaList = async () => {
  const res: any = await queryChildByTypeCodeAndItemValue({
    typeCode: "FAB_AREA"
  });
  areaList.value = res.filter(e => e.itemDesc.includes("FFU"));
};

let today = new Date();
const firstDayOfMonth = dayjs(new Date(today.getFullYear(), today.getMonth() - 3, 1)).format("YYYY-MM-DD");
// 获取当前月份最后一天
const lastDayOfMonth = dayjs(new Date(today.getFullYear(), today.getMonth() + 1, 0)).format("YYYY-MM-DD");
const dateRange = ref([firstDayOfMonth, lastDayOfMonth]);
const dateRange2 = ref([firstDayOfMonth, lastDayOfMonth]);
const loading = ref(true);
const ids = ref([]);
const tableRowInputRef: any = ref(null);

const data = reactive<Record<string, any>>({
  queryParams: {
    pageNum: 1,
    pageSize: 20
  },
  tableList: [],
  total: 0,
  colCount: 12
});

const { queryParams, total, tableList, colCount } = toRefs(data);

const addColCount = () => {
  colCount.value++;
};
/** 列表 */
const getList = async () => {
  loading.value = true;
  const res: any = await queryCountFilterUsage({
    className: "MACHINE",
    systemName: "FFU",
    orderInstallDateFrom: dateRange.value[0],
    orderInstallDateTo: dateRange.value[1],
    pageNum: 1,
    pageSize: 9999
  });
  tableList.value = res;
  loading.value = false;
};
const alignData = (list, data) => {
  let t = [];
  list.forEach(v => {
    let f = data.filter(item => item.date == v);
    if (f.length) {
      t.push(f[0].value);
    } else {
      t.push(null);
    }
  });
  return t;
};
const valueIsEmpty = value => {
  if (value === "" || value == null || typeof value == "undefined") {
    return true;
  }
  return false;
};
function generateDateRanges(startDate, endDate) {
  const dateRanges = [];
  let currentSDate = dayjs(startDate);
  let currentEDate = dayjs(endDate);
  while (currentSDate.isBefore(currentEDate)) {
    const formattedDate = currentSDate; // 格式为 "YYYY-MM-DD"
    dateRanges.push(formattedDate.format("YYYY-MM-DD HH:mm:ss"));
    currentSDate = currentSDate.add(1, "day");
  }

  return dateRanges;
}
const getChartData = async () => {
  loading.value = true;
  const lineData: any = await ffuLifespan({
    startTime: dateRange2.value[0],
    endTime: dateRange2.value[1],
    area: activeArea.value,
    type: filterType.value
  });

  if ((!lineData.dataList || !lineData.dataList.length) && valueIsEmpty(lineData.ratedLife)) {
    chartOptions_1.value = null;
    loading.value = false;
    return;
  }
  let actualDates = lineData?.dataList?.map(v => v.date) || [];
  let rangeDates = generateDateRanges(dateRange2.value[0], dateRange2.value[1]);
  let dates = [...actualDates, ...rangeDates];
  let combinedDates = dates.sort((a, b) => {
    return dayjs(a).isBefore(dayjs(b)) ? -1 : 1;
  });
  let xAxisData = [...new Set(combinedDates)]; // 去重
  chartOptions_1.value = {
    title: {
      text: "Chemical Filter Lifespan Comparison in Different Cleanroom Areas",
      left: "center", // 调整标题的水平位置
      top: 0 // 调整标题的垂直位置
    },
    tooltip: {
      trigger: "axis"
    },
    legend: {
      data: ["Rated Lifespan", "Actual Lifespan"],
      top: "8%", // 调整图例的垂直位置
      left: "right" // 调整图例的水平位置
    },
    grid: {
      left: "8%",
      right: "5%",
      bottom: "3%",
      top: "18%",
      containLabel: true
    },
    toolbox: {
      feature: {
        saveAsImage: {}
      }
    },
    xAxis: {
      type: "category",
      boundaryGap: false,
      data: xAxisData,
      axisLabel: {
        // interval: 0, // 显示所有标签
        rotate: 45, // 旋转标签
        show: true
      }
    },
    yAxis: {
      type: "value"
    },
    series: [
      // {
      //   name: "AI Predicted Lifespan",
      //   type: "line",
      //   connectNulls: true,
      //   // stack: "Total",
      //   data: alignData(xAxisData, dd?.dataList || [])
      // },
      {
        name: "Rated Lifespan",
        type: "line",
        stack: "Total",
        connectNulls: true,
        showSymbol: false,
        data: xAxisData.map(v => lineData?.ratedLife)
      },
      {
        name: "Actual Lifespan",
        type: "line",
        // stack: "Total",
        connectNulls: true,
        data: alignData(xAxisData, lineData?.dataList) //[parseFloat(dd.lifecycle_act) + parseFloat(dd.lifecycle_act_left), dd.lifecycle_act_left]
      }
    ]
  };
  // chartRef1.value?.updateEchartsOption();
  chartRef1.value?.forceUpdateEcharts();
  loading.value = false;
};
onMounted(async () => {
  // queryAreaList();
  getList();
  // getChartData();
});

/** 重置按钮操作 */
const resetQuery = () => {
  dateRange.value = [firstDayOfMonth, lastDayOfMonth];
  proxy.resetForm("queryRef");
  getList();
};
const resetQuery2 = () => {
  dateRange2.value = [firstDayOfMonth, lastDayOfMonth];
  getChartData();
};

/** 多选框选中数据 */
// const handleSelectionChange = selection => {
//   ids.value = selection.map(item => item.id);
// };

/** 导出按钮操作 */
const handleExport = () => {
  if (dateRange.value != null && dateRange.value.length > 0) {
    let Token = getToken().accessToken || "";
    let url = `${VITE_FANRUAN_BASE_URL}/webroot/decision/view/report?viewlet=machine%252F%25E5%258C%2596%25E6%25BB%25A4%25E5%25AF%25BF%25E5%2591%25BD%25E7%25BB%25BC%25E5%2590%2588%25E6%258A%25A5%25E8%25A1%25A8.cpt&token=${Token}&startDate=${dateRange.value[0]}&endDate=${dateRange.value[1]}&count=${colCount.value}&format=excel&extype=simple&&apiHost=${window.location.protocol}//${window.location.hostname}&facCode=${localStorage.getItem("facCode") || ""}`;
    window.location.href = url;
  } else {
    PxMessage({
      message: "请选择时间后再导出",
      type: "error"
    });
  }
};
</script>
<style scoped lang="scss">
.box-shadow {
  padding: 20px;
  margin-bottom: 16px;
  background: #fff;
  // box-shadow: 0 0 10px 0 rgb(0 0 0 / 10%);
}

.box {
  display: flex;
  gap: 16px;
  height: 500px;
  overflow: hidden;

  .left,
  .right {
    flex: 1;
    height: 100%;
  }
}
</style>
